package io.github.fb513.api.controller;

import io.github.fb513.api.enums.RespMetaEnum;
import io.github.fb513.api.exception.WebBaseException;
import io.github.fb513.api.model.CommonResp;
import io.github.fb513.api.util.RespUtils;
import io.github.fb513.common.util.DateUtils;
import io.minio.MinioClient;
import io.minio.PostPolicy;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Autowired
    private MinioClient minioClient;
    @Value("${oss.bucket}")
    private String bucket;
    @Value("${oss.endpoint}")
    private String endpoint;

    @GetMapping("/policy")
    public CommonResp<?> getSign(String fileName) {
        String dir = DateUtils.formatLocalDate(LocalDate.now());
        String pic = dir + "/" + UUID.randomUUID() + "/" + fileName;
        try {
            PostPolicy postPolicy = new PostPolicy(bucket, ZonedDateTime.now().plusMinutes(10));
            postPolicy.addEqualsCondition("key", pic);
            postPolicy.addStartsWithCondition("Content-Type", "image/");
            postPolicy.addContentLengthRangeCondition(0, 64 * 1024 * 1024);
            Map<String, String> resMap = minioClient.getPresignedPostFormData(postPolicy);
            resMap.put("url", endpoint + "/" + bucket + "/" + pic);
            resMap.put("key", pic);
            return RespUtils.success(resMap);
        } catch (ServerException | InsufficientDataException | ErrorResponseException | IOException |
                 NoSuchAlgorithmException | InvalidKeyException | InvalidResponseException | XmlParserException |
                 InternalException e) {
            throw new WebBaseException(RespMetaEnum.TIMEOUT, e);
        }
    }
}
